import { getData } from '../../../plugins/getData'
import { defineEventHandler, getQuery } from 'h3'
import { replaceImageDomains } from '~/utils/configHelper'

export default defineEventHandler(async (event) => {
  try {
    // 获取查询参数
    const query = getQuery(event)
    // 解码参数
    // const mainCategory = decodeURIComponent(query.mainCategory as string)
    // const subCategory = decodeURIComponent(query.subCategory as string)
    const dataSource = query.dataSource as string // 可选参数，指定数据源

    // 获取mainCategory和subCategory，需解码decode
    const mainCategory = event.context.params?.mainCategory ? decodeURIComponent(event.context.params.mainCategory) : ''
    const subCategory = event.context.params?.subCategory ? decodeURIComponent(event.context.params.subCategory) : ''
    const cost = String(getQuery(event).cost || 'All')
    const appListPageSize = Number(query.appListPageSize) || 999999999;
    const appListPageCurrent = Number(query.appListPageCurrent) || 1;

    if (!mainCategory || !subCategory) {
      return {
        success: false,
        message: '一级分类和二级分类参数不能为空',
        data: [],
        total: 0
      }
    }

    // 使用插件提供的数据
    const { getCurrentRequestData, getDataSourceData } = getData()

    let categoryData: any = null

    if (dataSource) {
      // 如果指定了数据源，使用指定的数据源
      categoryData = getDataSourceData(dataSource)
    } else {
      // 否则使用当前域名的数据
      const currentData = getCurrentRequestData(event)
      if (currentData) {
        categoryData = currentData.data
      }
    }

    if (!categoryData) {
      return {
        success: false,
        message: '无法获取分类数据',
        data: [],
        total: 0
      }
    }

    // 检查一级分类是否存在
    if (!categoryData.mainCategories.includes(mainCategory)) {
      return {
        success: false,
        message: `一级分类 "${mainCategory}" 不存在`,
        data: [],
        total: 0,
        availableMainCategories: categoryData.mainCategories
      }
    }

    // 检查二级分类是否存在（如果二级分类为ALL，则跳过检查）
    const subCategories = categoryData.subCategories[mainCategory] || []
    if (!subCategories.includes(subCategory)) {
      return {
        success: false,
        message: `二级分类 "${subCategory}" 不存在`,
        data: [],
        total: 0,
        subCategory,
        availableSubCategories: subCategories
      }
    }

    // 获取指定一级分类下的app数据
    const categoryDataForMain = categoryData.categoryData[mainCategory] || {}
    let apps: any[] = []
    apps = categoryDataForMain[subCategory] || []

    if (cost === 'All') {
      apps = apps
    } else {
      apps = apps.filter((app) => app.cost === cost)
    }

    // 获取请求域名并替换图片域名
    const hostname = event.node.req.headers.host || ''
    const processedApps = replaceImageDomains(apps, hostname)

    const start = (appListPageCurrent - 1) * appListPageSize;
    const end = start + appListPageSize;

    return {
      success: true,
      message: `获取应用列表成功`,
      data: processedApps.slice(start, end),
      total: processedApps.length,
      subCategory,
      availableSubCategories: subCategories,
    };

  } catch (error: any) {
    console.error('获取应用列表错误:', error)
    return {
      success: false,
      message: '获取应用列表过程中发生错误',
      data: [],
      total: 0,
      error: process.env.NODE_ENV === 'development' ? error?.message : undefined
    }
  }
})